import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { parseLocalDate } from '../../utils/date'
import { z } from 'zod'

export default eventHandler(async (event) => {
  const q = getQuery(event)
  const schema = z.object({
    childId: z.string(),
    date: z.string() // YYYY-MM-DD
  })
  const parsed = schema.safeParse(q)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })

  const childId = Number(parsed.data.childId)
  if (!Number.isFinite(childId)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })

  await assertChildOwnership(event, childId)

  // 使用与创建记录时相同的日期解析方式
  const dateStr = parsed.data.date
  const targetDate = parseLocalDate(dateStr)

  // 查询活动记录
  const activityRecords = await prisma.activityRecord.findMany({
    where: {
      childId,
      date: targetDate
    },
    include: {
      activityTemplate: {
        select: {
          title: true
        }
      }
    },
    orderBy: { createdAt: 'asc' }
  })

  // 查询兑换记录
  const redemptions = await prisma.redemption.findMany({
    where: {
      childId,
      date: targetDate
    },
    include: {
      rewardTemplate: {
        select: {
          title: true
        }
      }
    },
    orderBy: { createdAt: 'asc' }
  })

  // 格式化活动记录
  const activities = activityRecords.map(record => ({
    id: record.id,
    templateTitle: record.activityTemplate.title,
    points: record.points,
    quantity: record.quantity,
    note: record.note,
    createdAt: record.createdAt
  }))

  // 格式化兑换记录
  const redemptionList = redemptions.map(redemption => ({
    id: redemption.id,
    rewardTitle: redemption.rewardTemplate.title,
    pointsCost: redemption.pointsCost,
    note: redemption.note,
    createdAt: redemption.createdAt
  }))

  // 计算统计
  const totalEarned = activities.reduce((sum, a) => sum + a.points, 0)
  const totalSpent = redemptionList.reduce((sum, r) => sum + r.pointsCost, 0)
  const netPoints = totalEarned - totalSpent

  return {
    date: dateStr,
    activities,
    redemptions: redemptionList,
    totalEarned,
    totalSpent,
    netPoints
  }
})
